import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class QuestionDAO {

    public List<Question> getQuestionsByExamId(int examId) {
        List<Question> questions = new ArrayList<>();
        String sql = "SELECT * FROM questions WHERE exam_id = ? ORDER BY question_order";

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Question question = new Question();
                    question.setId(rs.getInt("id"));
                    question.setExamId(rs.getInt("exam_id"));
                    question.setQuestionType(rs.getString("question_type"));
                    question.setQuestionText(rs.getString("question_text"));
                    question.setQuestionOrder(rs.getInt("question_order"));
                    question.setScore(rs.getDouble("score"));
                    question.setCorrectAnswer(rs.getString("correct_answer"));

                    questions.add(question);
                }
            }

            // 在ResultSet关闭后加载选项
            for (Question question : questions) {
                if (question.isChoiceQuestion()) {
                    question.setOptions(getQuestionOptions(question.getId()));
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return questions;
    }

    public List<QuestionOption> getQuestionOptions(int questionId) {
        List<QuestionOption> options = new ArrayList<>();
        String sql = "SELECT * FROM question_options WHERE question_id = ? ORDER BY option_label";

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, questionId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    QuestionOption option = new QuestionOption();
                    option.setId(rs.getInt("id"));
                    option.setQuestionId(rs.getInt("question_id"));
                    option.setOptionLabel(rs.getString("option_label"));
                    option.setOptionText(rs.getString("option_text"));
                    option.setCorrect(rs.getBoolean("is_correct"));
                    options.add(option);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return options;
    }

    public boolean createQuestion(Question question) {
        String sql = "INSERT INTO questions (exam_id, question_type, question_text, question_order, score, correct_answer) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setInt(1, question.getExamId());
            stmt.setString(2, question.getQuestionType());
            stmt.setString(3, question.getQuestionText());
            stmt.setInt(4, question.getQuestionOrder());
            stmt.setDouble(5, question.getScore());
            stmt.setString(6, question.getCorrectAnswer());

            int result = stmt.executeUpdate();
            if (result > 0) {
                ResultSet keys = stmt.getGeneratedKeys();
                if (keys.next()) {
                    question.setId(keys.getInt(1));
                }

                // 如果是选择题，保存选项
                if (question.isChoiceQuestion() && question.getOptions() != null) {
                    for (QuestionOption option : question.getOptions()) {
                        option.setQuestionId(question.getId());
                        createQuestionOption(option);
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean createQuestionOption(QuestionOption option) {
        String sql = "INSERT INTO question_options (question_id, option_label, option_text, is_correct) VALUES (?, ?, ?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, option.getQuestionId());
            stmt.setString(2, option.getOptionLabel());
            stmt.setString(3, option.getOptionText());
            stmt.setBoolean(4, option.isCorrect());

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteQuestionOptions(int questionId) {
        String sql = "DELETE FROM question_options WHERE question_id = ?";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, questionId);
            return stmt.executeUpdate() >= 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteQuestionsByExamId(int examId) {
        String sql = "DELETE FROM questions WHERE exam_id = ?";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examId);
            return stmt.executeUpdate() >= 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateQuestion(Question question) {
        String sql = "UPDATE questions SET question_type = ?, question_text = ?, score = ?, correct_answer = ? WHERE id = ?";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, question.getQuestionType());
            stmt.setString(2, question.getQuestionText());
            stmt.setDouble(3, question.getScore());
            stmt.setString(4, question.getCorrectAnswer());
            stmt.setInt(5, question.getId());

            int result = stmt.executeUpdate();
            if (result > 0) {
                // 如果是选择题，更新选项
                if (question.isChoiceQuestion()) {
                    deleteQuestionOptions(question.getId());
                    if (question.getOptions() != null) {
                        for (QuestionOption option : question.getOptions()) {
                            option.setQuestionId(question.getId());
                            createQuestionOption(option);
                        }
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Question getQuestionById(int questionId) {
        String sql = "SELECT * FROM questions WHERE id = ?";
        Question question = null;

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, questionId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    question = new Question();
                    question.setId(rs.getInt("id"));
                    question.setExamId(rs.getInt("exam_id"));
                    question.setQuestionType(rs.getString("question_type"));
                    question.setQuestionText(rs.getString("question_text"));
                    question.setQuestionOrder(rs.getInt("question_order"));
                    question.setScore(rs.getDouble("score"));
                    question.setCorrectAnswer(rs.getString("correct_answer"));
                }
            }

            // 在ResultSet关闭后加载选项
            if (question != null && question.isChoiceQuestion()) {
                question.setOptions(getQuestionOptions(question.getId()));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return question;
    }
}